//
//  HomeViewModel.swift
//  aishop
//
//  Created by tuguowei on 2025/10/15.
//

import Foundation
import Combine

@MainActor
class HomeViewModel: ObservableObject {
    @Published var banners: [BannerItem] = []
    @Published var menus: [MenuItem] = []
    @Published var coupons: [Coupon] = []
    @Published var products: [Product] = []
    @Published var isLoading = false
    @Published var errorMessage: String?
    
    private let apiService = APIService.shared
    private var cancellables = Set<AnyCancellable>()
    
    func loadData() async {
        isLoading = true
        errorMessage = nil
        
        do {
            // 并发加载多个数据
            async let indexData = try await loadIndexData()
            async let couponsData = try await loadCoupons()
            
            let (index, coupons) = try await (indexData, couponsData)
            
            // 更新UI数据
            self.banners = index.banner ?? []
            self.menus = index.menus ?? []
            // 合并所有商品列表，优先显示热门、新品、优惠商品
            var allProducts: [Product] = []
            allProducts.append(contentsOf: index.hot ?? [])
            allProducts.append(contentsOf: index.new ?? [])
            allProducts.append(contentsOf: index.benefit ?? [])
            allProducts.append(contentsOf: index.good ?? [])
            allProducts.append(contentsOf: index.lovely ?? [])
            allProducts.append(contentsOf: index.bastList ?? [])
            allProducts.append(contentsOf: index.firstList ?? [])
            self.products = allProducts
            self.coupons = coupons
            
        } catch {
            self.errorMessage = error.localizedDescription
        }
        
        isLoading = false
    }
    
    private func loadIndexData() async throws -> IndexData {
        let response = try await apiService.fetchIndexData()
        if response.isSuccess, let data = response.data {
            return data
        } else {
            throw APIError.serverError(response.message ?? "Unknown error")
        }
    }
    
    private func loadCoupons() async throws -> [Coupon] {
        let response = try await apiService.fetchCoupons(type: "1", category: 0, merId: 0)
        if response.isSuccess, let data = response.data {
            return data.list
        } else {
            throw APIError.serverError(response.message ?? "Unknown error")
        }
    }
    
    func refreshData() async {
        await loadData()
    }
}